<script setup lang="ts">
  import { ref, nextTick, inject, computed, onMounted } from 'vue'
  import Header from './component/header.vue'
  import Default from './component/default.vue'
  import Footer from './component/footer.vue'
  import ChatItem from './component/chatItem.vue'
  import History from './component/history.vue'
  import { showHistoryKey, type AgentItem } from './types'
  // import { AGENT_LIST } from './utils/constant'
  const props = defineProps<{
    userName: string
    greeting: string
    chatApi: string
    apiKey: string
    user: string
    agentList: AgentItem[]
  }>()

  // 控制是否显示默认界面
  const isDefault = ref(true)
  // 创建新的对话，flag为true时显示默认界面
  const createDialog = (flag = false) => {
    isDefault.value = flag
    if (chatItemRef.value) {
      chatItemRef.value.clearChat()
    }
    if (footerRef.value) {
      footerRef.value.clearInput()
    }
  }

  // 处理发送消息
  const handleSend = async (message: string) => {
    if (isDefault.value) {
      isDefault.value = false
    }
    await nextTick(() => {
      chatItemRef.value?.startChat(message)
    })
  }

  // 处理停止生成
  const handleStop = () => {
    console.log('stop')
    chatItemRef.value?.handleCancel()
  }

  // 是否正在发送消息
  const isSending = ref(false)
  // 聊天组件引用
  const chatItemRef = ref<InstanceType<typeof ChatItem> | null>(null)

  // const showHistory = ref(false)
  // const toggleHistory = () => {
  //   showHistory.value = !showHistory.value
  // }
  // 注入全局状态和方法
  const {
    showHistory,
    toggleHistory,
    fullScreen,
    toggleFullScreen,
    closeAgent,
    handleAgentNav,
    getToken,
  } = inject(showHistoryKey)!

  // 组件挂载时获取token
  onMounted(async () => {
    if (getToken) {
      getToken()
    }
  })

  // 底部组件引用
  const footerRef = ref<InstanceType<typeof Footer> | null>(null)
  // 发送消息
  const sendMsg = () => {
    isSending.value = true
    footerRef.value?.clearInput()
  }

  // 完成消息发送
  const finish = () => {
    isSending.value = false
  }

  // 当前选中的智能体
  const currentAgent = ref<AgentItem | null>(null)
  // 处理智能体点击事件
  const handleAgentClick = (item: { name: string; icon: string; apiKey: string }) => {
    currentAgent.value = item
  }

  // 计算聊天标题
  const chatTitle = computed(() => {
    if (chatItemRef.value && chatItemRef.value.chatList.length > 0) {
      return chatItemRef.value.chatList[0].content ?? ''
    }
    return ''
  })

  // 创建设备健康检查对话，根据不同智能体，暴露不同方法
  const createDeviceHealthDialog = async (deviceId: string, label: string) => {
    // createDialog(true)
    currentAgent.value = props.agentList[2]
    createDialog(false)
    console.log('createDeviceHealthDialog', deviceId, label)
    await nextTick(() => {
      // chatItemRef.value?._changeDeviceId(deviceId)
      chatItemRef.value?.startChat(label, -1, deviceId)
    })
  }

  defineExpose({
    createDeviceHealthDialog,
    handleAgentClick,
  })
</script>

<template>
  <div class="deepseek-chat flex justify-between">
    <div class="deepseek-chat-left" :class="{ '!w-[240px]': showHistory }">
      <History
        :show-history="showHistory"
        @createDialog="createDialog"
        @toggleHistory="toggleHistory"
      />
    </div>
    <div
      class="deepseek-chat-container relative"
      :class="{
        '!w-[calc(100%-240px)]': showHistory,
        'is-default': isDefault,
        'is-chat': !isDefault,
      }"
    >
      <Header
        :is-full-screen="fullScreen || false"
        @close="closeAgent"
        @fullScreen="toggleFullScreen"
        :is-default="isDefault"
        :chat-title="chatTitle"
      />
      <div class="deepseek-chat-container-content my-6" v-if="currentAgent">
        <Default
          v-if="isDefault"
          :currentIcon="currentAgent.icon"
          @agentClick="handleAgentClick"
          :greeting="props.greeting"
          :userName="props.userName"
          :fullScreen="fullScreen || false"
          :agentList="props.agentList"
        />
        <ChatItem
          :fullScreen="fullScreen || false"
          @sendMsg="sendMsg"
          @finish="finish"
          ref="chatItemRef"
          @agentNav="handleAgentNav"
          :key="currentAgent.apiKey"
          v-else
          :user="props.user"
          :chatApi="props.chatApi"
          :apiKey="currentAgent.apiKey"
          :agent="currentAgent.icon"
        />
      </div>
      <div class="px-6">
        <Footer
          :fullScreen="fullScreen || false"
          ref="footerRef"
          @send="handleSend"
          @stop="handleStop"
          :is-sending="isSending"
          @createDialog="createDialog"
        />
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
  @import './assets/styles/deepseek-chat.less';
</style>
